<script setup>

import {getCurrentInstance, reactive, ref, watch} from "vue";
import {enumToArray} from "@/utils/utils";
import {userGenderList} from "@/enum/enum";
import {cloneDeep} from "lodash";
import {updateSysUser} from "@/api/system/user";

const props = defineProps({
  user: {
    type: Object,
    default: {}
  }
})
const {proxy} = getCurrentInstance();
const formRef = ref();
const formData = ref();
const userGenderOptions = enumToArray(userGenderList)
const emit = defineEmits(['success'])

const rules = reactive({
  nickName: [{required: true, message: '请输入用户昵称', trigger: 'blur'}],
  email: [
    {
      pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ],
  phonenumber: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur'
    },
    {
      pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
})

const handleSubmit = async () => {
  await formRef.value.validate();
  let data = cloneDeep(formData.value);
  await updateSysUser(data);
  proxy.$modal.okNotify('修改成功');
  emit('success');
}

watch(() => props.user, (newVal) => {
  if (newVal) {
    formData.value = {...newVal}
  }
}, {immediate: true})
</script>

<template>
  <a-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
    <a-form-item label="用户昵称" name="nickName">
      <a-input v-model:value="formData.nickName" placeholder="请输入用户昵称"/>
    </a-form-item>
    <a-form-item label="电子邮箱" name="email">
      <a-input v-model:value="formData.email" placeholder="请输入电子邮件"/>
    </a-form-item>
    <a-form-item label="手机号码" name="phonenumber">
      <a-input v-model:value="formData.phonenumber" placeholder="请输入手机号码"/>
    </a-form-item>
    <a-form-item label="性别" name="sex">
      <a-radio-group v-model:value="formData.sex" placeholder="请选择用户性别">
        <a-radio v-for="item in userGenderOptions" :key="item.value" :value="item.value">{{item.label}}</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item>
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </a-form-item>
  </a-form>
</template>

<style scoped lang="scss">

</style>
